package array;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * Created by fengliejv on 2017/12/4.
 */
public class FractiontoRecurringDecimal166 {
    public String fractionToDecimal(int numerator, int denominator) {

        long numerators = numerator;
        long denominators = denominator;
        Map<Long, Integer> resMap = new HashMap();

        StringBuilder result = new StringBuilder();
        if(numerators<0&&denominators>0 || numerators>0&&denominators<0){
            result.append("-");
        }
        numerators = Math.abs(numerators);
        denominators = Math.abs(denominators);

        result.append(numerators / denominators);
        long res = numerators % denominators;

        if (res != 0) {
            result.append(".");
        }

        StringBuilder sb = new StringBuilder();
        while (res != 0 && !resMap.containsKey(res)) {
            resMap.put(res, sb.length());
            res = res * 10;
            sb.append(res / denominators);
            res = res % denominators;
        }
        if (res != 0) {
            int index = resMap.get(res);
            result.append(sb.subSequence(0, index));
            result.append("(");
            result.append(sb.subSequence(index, sb.length()));
            result.append(")");
        } else {
            result.append(sb);
        }
        return result.toString();
    }
}
